package service

import (
	"context"
	"errors"
	appsv1 "k8s.io/api/apps/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"log"
)

type daemonset struct {}

var Daemonset daemonset


//类型转换方法 corev1.Pod -> DataCell
func (d *daemonset) toCell(daemonsets []appsv1.DaemonSet) []DataCell {
	cell := make([]DataCell, len(daemonsets))
	for i := range daemonsets {
		cell[i] = daemonsetCell(daemonsets[i])
	}
	return cell
}

//类型转换方法  DataCell -> appsv1.DaemonSet
func (d *daemonset) fromCells(cells []DataCell) []appsv1.DaemonSet {
	daemonsets := make([]appsv1.DaemonSet, len(cells))
	for i := range cells {
		// cells[i].(deploymentCell) 类型转换
		daemonsets[i] = appsv1.DaemonSet(cells[i].(daemonsetCell))

	}
	return daemonsets
}

//定义列表的返回内容 Item是deploy元素列表  Total为元素数量
type DaemonsetResp struct {
	Item  []appsv1.DaemonSet `json:"item"`
	Total int                 `json:"total"`
}

//获取 daemonset 列表 支持过滤 排序 分页
func (d *daemonset) GetDaemonsets(filtername, namespacen string, limit, page int) (daemonsetResp *DaemonsetResp, err error) {
	//获取deploymentList类型的deploy列表
	daemonsetList, err := K8s.ClientSet.AppsV1().DaemonSets(namespacen).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		log.Printf("[ Daemonset ]资源列表获取失败：%s", err)
		return nil, errors.New("获取 [Daemonset] 列表失败" + err.Error())
	}

	selectableData := &dataSelector{
		GenericDataList: d.toCell(daemonsetList.Items),
		DataSelectQuery: &DataSelectQuery{
			FilterQuery: &FilterQuery{Name: filtername},
			PaginateQuary: &PaginateQuary{
				Limit: limit,
				Page:  page,
			},
		},
	}

	//先过滤
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	//先排序再分页
	data := filtered.Sort().Paginate()

	daemonsets := d.fromCells(data.GenericDataList)

	return &DaemonsetResp{
		Total: total,
		Item:  daemonsets,
	}, nil

}


//获取 daemonset 详情
func (d *daemonset) GetDaemonDetail(daemonName, namespace string) (daemonset *appsv1.DaemonSet, err error) {

	daemonset, err = K8s.ClientSet.AppsV1().DaemonSets(namespace).Get(context.TODO(), daemonName, metav1.GetOptions{})
	if err != nil {
		log.Printf("获取[ daemonset ]详情失败：%s", err)
		return nil, errors.New("获取[ daemonset ]详情失败：%s" + err.Error())
	}
	return daemonset, nil
}

//删除daemonset
func (d *daemonset)DelDaemonset(daemonName, namespace string) error {
	err := K8s.ClientSet.AppsV1().DaemonSets(namespace).Delete(context.TODO(),daemonName,metav1.DeleteOptions{})
	if err != nil {
		log.Printf("删除[daemonset]失败：%s", err)
		return  errors.New("删除[daemonset]失败：%s" + err.Error())
	}
	return nil
}